//
//  RegisterViewController.m
//  QGZone
//
//  Created by xiabin on 15/8/14.
//  Copyright (c) 2015年 Olive.Banana. All rights reserved.
//

#import "RegisterViewController.h"
#import "ServerCodecDef.h"
#import "UMNetworkManager.h"
#import "HardwareService.h"
#import "WebViewController.h"
#import "AppDelegate.h"
#import "UMServer.h"
#import "UserModel.h"

@interface RegisterViewController () {
    NSTimer* myTimer;
    int timeLeft;
    int getPwdJobId;
    int loginJobId;
    int thirdJobId;
    int retry;
    int querySelfInfo;
    int bQQ;
    UserModel* userInfo;
}

@end

@implementation RegisterViewController

#pragma mark life cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.phoneNumber];
    [self.view addSubview:self.verifiCode];
    [self.view addSubview:self.verifiCodeBtn];
    [self.view addSubview:self.registerBtn];
    [self.view addSubview:self.logoImage];
    
    [self layoutSubViews];

    [self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(endEdit)]];
    [self.view setBackgroundColor:QGPageBG];
    timeLeft = 59;
    
    /*[self setAutomaticallyAdjustsScrollViewInsets:NO];
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
        [self setEdgesForExtendedLayout:UIRectEdgeNone];
        [self setExtendedLayoutIncludesOpaqueBars:NO];
    }*/
}

-(void) viewWillAppear:(BOOL)animated {
    [self initNavigationStyle];
}

-(void) viewWillDisappear:(BOOL)animated {
}

#pragma mark ui event response
- (void)cancelReg {
    [self.navigationController popViewControllerAnimated:YES];
}

-(void) onBtnReg {
    
    NSDictionary *user = [NSDictionary dictionaryWithObjectsAndKeys:
                          self.phoneNumber.text, kUserName,
                          self.verifiCode.text , kUserPwd,
                          nil];
    
    NSError *error;
    if ([NSJSONSerialization isValidJSONObject:user])
    {
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:user options:NSJSONWritingPrettyPrinted error: &error];
        NSMutableData *tempJsonData = [NSMutableData dataWithData:jsonData];
        loginJobId = [QGNetworkManager LoginWithNameAndPwd:tempJsonData Callback:self];
    }
    
}

-(void) onBtnGetVerifiCode {
    getPwdJobId = [QGNetworkManager GetPwd:self.phoneNumber.text Callback:self];
    [self.verifiCodeBtn setBackgroundColor:QGRegBtnBGGray];
    myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
}

#pragma mark ui ctrl delegate
-(void)onTimer:(NSTimer *)timer
{
    if (timeLeft > 0) {
        NSString* strTimeLeft = [NSString stringWithFormat:@"%d秒",timeLeft-1];
        [_verifiCodeBtn setTitle:strTimeLeft forState:UIControlStateNormal];
        timeLeft-=1;
    } else {
        [self.verifiCodeBtn setTitle:@"重新获取" forState:UIControlStateNormal];
        [self.verifiCodeBtn setBackgroundColor:QGRegBtnBGNormal];
        timeLeft = 59;
        retry = 1;
        [myTimer invalidate];
    }
}

#define NUMBERS @"0123456789"
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSInteger strLength = textField.text.length - range.length + string.length;
    
    if (textField == self.verifiCode) {
        if (strLength >= 6) {
            [_registerBtn setBackgroundColor:QGNavBG];
            self.registerBtn.enabled = YES;
        } else {
            [_registerBtn setBackgroundColor:QGRegBtnBGGray];
            self.registerBtn.enabled = NO;
        }
        if (strLength > 6) return NO;
    } else {
        if (strLength < 11) {
            [_verifiCodeBtn setBackgroundColor:QGRegBtnBGGray];
            self.verifiCodeBtn.enabled = NO;
        }
        if (strLength > 11) {
            return NO;
        }
    }
    
    NSCharacterSet*cs;
    cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];
    NSString* filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    BOOL basicTest = [string isEqualToString:filtered];
    if(!basicTest) {
        return NO;
    }
    if (!self.verifiCodeBtn.enabled && strLength == 11) {
        [_verifiCodeBtn setBackgroundColor:QGNavBG];
        self.verifiCodeBtn.enabled = YES;
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark custom delegate
-(void) UMAsyncJobDone:(UMJobStatus)emJobStatus JobCookie:(int)JobID And:(id)JobRet {
    [self hideHud];
    if (emJobStatus == FAILED)
    {
        //激活任务失败
        if (JobID == getPwdJobId) {
            [Utils TTAlertNoTitle:@"获取验证码失败"];
        } else {
            [Utils TTAlertNoTitle:@"保存资料失败!"];
        }
        return;
    }
    NSDictionary *user = JobRet;
    if (JobID == loginJobId) {
        if ([Utils Dictionary:user ContainsDicKey:kUserClass]) {
            user = user[kUserClass];
            int uid = (int)[user[kUserUID] integerValue];
            [QGHardwareService setUserid:uid];
            [QGHardwareService setUsername:self.phoneNumber.text];
            [QGHardwareService setUserpw:self.verifiCode.text];
        } else {
            [Utils TTAlertNoTitle:@"密码错误！请重试"];
        }
    }
}


#pragma mark private methods

- (void)hideHud{
    //[[self HUD] hide:YES];
}

-(void) endEdit {
    [self.verifiCode endEditing:NO];
    [self.phoneNumber endEditing:NO];
}


-(void) layoutSubViews {
    //顶部排布
    __weak __typeof(&*self)weakSelf = self;
    
    [self.verifiCodeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(weakSelf.view.mas_top).offset(NavH+10);
        //make.left.mas_equalTo(weakSelf.phoneNumber.mas_right).offset(0);
        make.right.mas_equalTo(weakSelf.view.mas_right).offset(0);
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(SCREEN_SIZE_WIDTH*0.35);
    }];
    
    [self.phoneNumber mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(weakSelf.verifiCodeBtn.mas_top);
        make.left.mas_equalTo(weakSelf.view.mas_left).offset(0);
        make.right.mas_equalTo(weakSelf.verifiCodeBtn.mas_left).offset(0);
        make.height.mas_equalTo(50);
        //make.width.mas_equalTo(SCREEN_SIZE_WIDTH*0.55);
    }];
    
    [self.verifiCode mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(weakSelf.phoneNumber.mas_bottom).offset(2);
        make.left.mas_equalTo(weakSelf.view.mas_left).offset(0);
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(SCREEN_SIZE_WIDTH);
    }];
    
    [self.registerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(weakSelf.view.mas_top).offset(200);
        make.centerX.mas_equalTo(weakSelf.view.mas_centerX);
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(weakSelf.view.mas_width).offset(-80);
    }];
    
    [self.logoImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(weakSelf.view.mas_bottom).offset(-30);
        make.centerX.mas_equalTo(weakSelf.view.mas_centerX).offset(0);
    }];
}

- (void) initNavigationStyle {
    UIView *statusBarView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_SIZE_WIDTH, 20)];
    statusBarView.backgroundColor=QGNavBG;
    [self.view addSubview:statusBarView];
    
    self.navigationController.navigationBar.backgroundColor = QGNavBG;
    self.navigationController.navigationBar.barTintColor = QGNavBG;
    
    UIButton* cancelBtn = [Utils NavButtonStyleNormalBLeft:YES NormalImg:@"back" AndHightLight:@"back"];
    [cancelBtn addTarget:self action:@selector(cancelReg) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:cancelBtn];
    self.navigationItem.title = @"登录/注册";
}

#pragma mark getter and setter

-(UITextField*) phoneNumber {
    if (_phoneNumber == nil) {
        _phoneNumber = [[UITextField alloc] init];
        _phoneNumber.delegate = self;
        _phoneNumber.placeholder = @"请输入手机号";
        [_phoneNumber setValue:QGTextGrayL1 forKeyPath:@"_placeholderLabel.textColor"];
        [_phoneNumber setValue:[UIFont systemFontOfSize:[Utils phoneFontL4]] forKeyPath:@"_placeholderLabel.font"];
        _phoneNumber.font = [UIFont systemFontOfSize:[Utils phoneFontL4]];
        _phoneNumber.backgroundColor = [UIColor whiteColor];
        _phoneNumber.returnKeyType = UIReturnKeyDone;
        UIImageView* leftView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 50)];
        leftView1.backgroundColor = [UIColor whiteColor];
        leftView1.image = [UIImage imageNamed:@"phone"];
        [leftView1 setContentMode:UIViewContentModeCenter];
        _phoneNumber.leftView = leftView1;
        _phoneNumber.leftViewMode = UITextFieldViewModeAlways;
    }
    return _phoneNumber;
}

-(UITextField*) verifiCode {
    if (_verifiCode == nil) {
        _verifiCode = [[UITextField alloc] init];
        _verifiCode.delegate = self;
        _verifiCode.placeholder = @"输入动态密码";
        [_verifiCode setValue:QGTextGrayL1 forKeyPath:@"_placeholderLabel.textColor"];
        [_verifiCode setValue:[UIFont systemFontOfSize:[Utils phoneFontL4]] forKeyPath:@"_placeholderLabel.font"];
        _verifiCode.font = [UIFont systemFontOfSize:[Utils phoneFontL4]];
        [_verifiCode setBackgroundColor:[UIColor whiteColor]];
        _verifiCode.returnKeyType = UIReturnKeyDone;
        UIImageView* leftView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 50)];
        leftView1.backgroundColor = [UIColor whiteColor];
        leftView1.image = [UIImage imageNamed:@"verifyCode"];
        _verifiCode.leftView = leftView1;
        [leftView1 setContentMode:UIViewContentModeCenter];
        _verifiCode.leftViewMode = UITextFieldViewModeAlways;
    }
    return _verifiCode;
}

-(UIButton*) verifiCodeBtn {
    if (_verifiCodeBtn == nil) {
        _verifiCodeBtn = [[UIButton alloc] init];
        [_verifiCodeBtn setTitle:@"获取动态密码" forState:UIControlStateNormal];
        [_verifiCodeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_verifiCodeBtn setBackgroundColor:QGRegBtnBGGray];
        _verifiCodeBtn.titleLabel.font = [UIFont systemFontOfSize:[Utils phoneFontL4]];
        [_verifiCodeBtn addTarget:self action:@selector(onBtnGetVerifiCode) forControlEvents:UIControlEventTouchUpInside];
        _verifiCodeBtn.enabled = NO;
        //_verifiCodeBtn.backgroundColor = [UIColor grayColor];

    }
    return _verifiCodeBtn;
}

-(UIButton*) registerBtn {
    if (_registerBtn == nil) {
        _registerBtn = [[UIButton alloc] init];
        [_registerBtn setTitle:@"确定" forState:UIControlStateNormal];
        [_registerBtn setTitleColor:QGTextWhite forState:UIControlStateNormal];
        [_registerBtn setTitleColor:QGTextGrayL1 forState:UIControlStateHighlighted];
        [_registerBtn setBackgroundColor:QGRegBtnBGGray];
        _registerBtn.enabled = NO;
        _registerBtn.titleLabel.font = [UIFont systemFontOfSize:[Utils phoneFontL6]];
        [_registerBtn addTarget:self action:@selector(onBtnReg) forControlEvents:UIControlEventTouchUpInside];
        [_registerBtn.layer setCornerRadius:4];
    }
    return _registerBtn;
}

-(UIImageView*) logoImage {
    if (_logoImage == nil) {
        _logoImage = [[UIImageView alloc] init];
        _logoImage.image = [UIImage imageNamed:@"deslabel"];
    }
    return _logoImage;
}

@end
